<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            clearable
            :placeholder="$t('pleaseEnterTheCategoryName')"
            prefix-icon="el-icon-search"
            size="small"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            ref="tree"
            :data="deptOptions"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :props="defaultProps"
            default-expand-all
            highlight-current
            node-key="id"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form
          v-show="showSearch"
          ref="queryForm"
          :inline="true"
          :model="queryParams"
          label-width="80px"
          size="small"
        >
          <el-form-item
            label-width="auto"
            :label="$t('productName')"
            prop="productName"
          >
            <el-input
              v-model="queryParams.productName"
              clearable
              :placeholder="$t('pleaseEnterTheProductName')"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="$t('publish')" prop="isPublish">
            <el-select
              v-model="queryParams.isPublish"
              :placeholder="$t('pleaseEnterState')"
            >
              <el-option
                v-for="dict in dict.type.menu_product_publish"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button
              icon="el-icon-search"
              size="mini"
              type="primary"
              @click="handleQuery"
            >{{ $t("search") }}</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
                $t("reset")
              }}</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:products:add']"
              icon="el-icon-plus"
              plain
              size="mini"
              type="primary"
              @click="handleAdd"
            >{{ $t("add") }}
            </el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:user:remove']"
            >{{ $t("delete") }}</el-button
            >
          </el-col>

          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>
        <el-table
          v-loading="loading"
          :data="productsList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column align="center" type="selection" width="55" />
          <!--          <el-table-column label="产品ID" align="center" prop="productId" />-->
          <el-table-column
            align="center"
            :label="$t('productName')"
            prop="productName"
          />

          <el-table-column
            align="center"
            class-name="small-padding fixed-width"
            :label="$t('controls')"
          >
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['system:products:query']"
                icon="el-icon-edit"
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
              >{{ $t("edit") }}
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:type:remove']"
              >{{ $t("delete") }}</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :limit.sync="queryParams.pageSize"
          :page.sync="queryParams.pageNum"
          :total="total"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      append-to-body
      center
      width="1100px"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="180px">
        <el-row align="center">
          <el-col :span="24">
            <el-form-item
              :label="$t('selectTheProductTypeTemplate')"
              prop="typetemplateValue"
            >
              <el-select
                @change="handleTypeTempClick()"
                v-model="typetemplateValue"
                :placeholder="$t('pleaseSelectTheProductCategoryTemplate')"
                :disabled="isAdd"
              >
                <el-option
                  v-for="item in typetemplateList"
                  :key="item.protypeId"
                  :label="item.remark"
                  :value="item.protypeId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="typetemplateValue">
          <el-row>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item :label="$t('productAttribute')"> </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple-light"></div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item :label="$t('productName')" prop="productName">
                  <el-input
                    v-model="form.productName"
                    clearable
                    :placeholder="$t('pleaseEnterTheProductName')"
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple-light">
                <el-form-item
                  :label="$t('recommendedProduct')"
                  prop="heartbeatProduct"
                >
                  <el-select
                    v-model="form.heartbeatProduct"
                    multiple
                    :placeholder="$t('pleaseSelectTheRecommendedProduct')"
                    style="width: 345px"
                  >
                    <el-option
                      v-for="item in heartbeatProduct"
                      :key="item.productId"
                      :label="item.productName"
                      :value="item.productId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item :label="$t('state')" prop="status">
                  <el-select
                    v-model="form.status"
                    :placeholder="$t('pleaseEnterState')"
                  >
                    <el-option
                      v-for="dict in dict.type.menu_product_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple-light">
                <el-form-item :label="$t('description')" prop="description">
                  <el-input
                    v-model="form.description"
                    clearable
                    :placeholder="$t('pleaseEnterProductDescription')"
                    @keyup.enter.native="handleQuery"
                    type="textarea"
                  />
                </el-form-item>
              </div>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item :label="$t('publish')" prop="isPublish">
                  <el-select
                    v-model="form.isPublish"
                    :placeholder="$t('pleaseEnterState')"
                  >
                    <el-option
                      v-for="dict in dict.type.menu_product_publish"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12" v-if="this.form.isPublish == '1'">
              <div class="grid-content bg-purple-light">
                <el-form-item :label="$t('selling')" prop="sellingPoint">
                  <el-input
                    v-model="form.sellingPoint"
                    clearable
                    :placeholder="$t('pleaseEnterTheSellingPointOfTheProduct')"
                    @keyup.enter.native="handleQuery"
                    type="textarea"
                  />
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" v-if="this.form.isPublish == '1'">
              <div class="grid-content bg-purple-light">
                <el-form-item :label="$t('sort')" prop="orderNum">
                  <el-input
                    v-model="form.orderNum"
                    clearable
                    :placeholder="$t('pleaseEnterASort')"
                    min="0"
                    @keyup.enter.native="handleQuery"
                    type="number"
                  />
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item
                  :label="$t('listOfProductDetails')"
                  prop="productFile"
                >
                  <file-pdf v-model="form.productFile" />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item
                  :label="$t('productDetailList(notAvailableForDownload)')"
                  prop="productNodFile"
                >
                  <file-pdf v-model="form.productNodFile" />
                </el-form-item>
              </div>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item :label="$t('attachment')" prop="productZip">
                  <fileUpload v-model="form.productZip" />
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item :label="$t('authorizedUser')" prop="roles">
                  <el-select
                    v-model="form.roles"
                    multiple
                    :placeholder="$t('pleaseSelectTheViewableRole')"
                  >
                    <el-option
                      v-for="item in receptionRole"
                      :key="item.roleId"
                      :label="item.roleName"
                      :value="item.roleId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item :label="$t('productModel')">
                  <el-tree
                    ref="menu"
                    :data="deptAddOptions"
                    :props="defaultProps"
                    class="tree-border"
                    :empty-text="$t('loadingPleaseWait')"
                    node-key="id"
                    show-checkbox
                  >
                  </el-tree>

                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item :label="$t('picture')" prop="informtAttachment">
                  <image-upload v-model="form.productImg" />
                </el-form-item>
              </div>
            </el-col>
          </el-row>

          <template v-if="typeTempDetails.basicAttribute">
            <el-row>
              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item :label="$t('basicAttributes')"> </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light"></div>
              </el-col>
            </el-row>
            <el-row>
              <el-col
                :span="12"
                v-for="item in typeTempDetails.basicAttribute"
                :key="item.basicattributeProd"
              >
                <div class="grid-content bg-purple">
                  <el-form-item
                    :label="item.basicattributeLabel"
                    :prop="basicForm[item.basicattributeProd]"
                  >
                    <el-input
                      v-model="basicForm[item.basicattributeProd]"
                      clearable
                      :placeholder="`${$t('input')} ${
                        item.basicattributeLabel
                      }`"
                    />
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
          </template>

          <template v-if="typeTempDetails.publicAttribute">
            <el-row>
              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item :label="$t('publicProperty')"> </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light"></div>
              </el-col>
            </el-row>
            <el-row>
              <el-col
                :span="12"
                v-for="item in typeTempDetails.publicAttribute"
                :key="item.publicattributeId"
              >
                <div class="grid-content bg-purple">
                  <el-form-item
                    :label="item.publicattributeName"
                    :prop="publicAttribute[item.publicattributeType]"
                  >
                    <el-select
                      v-model="publicAttribute[item.publicattributeType]"
                      :placeholder="`${$t('select')}${
                        item.publicattributeName
                      }`"
                      style="width: 345px"
                    >
                      <el-option
                        v-for="item2 in item.menuPublicattributeDatas"
                        :key="item2.publicattributeValue"
                        :label="item2.publicattributeLabel"
                        :value="item2.publicattributeValue"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
          </template>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t("ok") }}</el-button>
        <el-button @click="cancel">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
  </div>
</template>

<script>
import {
  changeUserStatus,
  delUser,
  deptTreeSelect,
} from "@/api/system/menuInformtype";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  typetemplates,
  findTypetemplateList,
} from "@/api/system/typetemplate";
import {
  addProducts,
  getProducts,
  getProductsAdd,
  listProducts,
  updateProducts,
  delProducts,
  findProductIds,
  typetemplatesProduct,
} from "@/api/system/products";
import {addType, delType, getType, listType, refreshCache, updateType} from "@/api/system/dict/type";
export default {
  name: "User",
  dicts: ["menu_product_publish", "menu_product_status"],

  components: { Treeselect },
  data() {
    return {
      publicAttribute: {},
      publicattributeLabel: {},
      basicForm: {},
      basicFormLabel: {},
      // {basicAttribute ,publicAttribut}
      typeTempDetails: null,
      typetemplateValue: null,
      typetemplateList: [],
      receptionRole: [],
      heartbeatProduct: [],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项

      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      openDataScopeE: false,
      menuExpandE: false,
      menuNodeAllE: false,
      deptExpand: true,
      deptNodeAll: false,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      productsList: [],
      // 岗位选项
      deptOptions: [],

      /*增加选项*/
      deptAddOptions: [],
      // 角色选项
      products: [],

      isAdd: false,
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/products/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        productModel: null,
        productModelE: null,
        productFile: null,
        isPublish: null,
      },
      // 列信息
      columns: [
        { key: 0, label: `产品名称`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true },
      ],
      rules: {
        roles: [
          {
            required: true,
            message: this.$t("theLookupRoleCannotBeEmpty"),
            trigger: "blur",
          },
        ],
        commonRoles: [
          {
            required: true,
            message: this.$t("theDataCannotBeEmpty"),
            trigger: "blur",
          },
        ],
        productName: [
          {
            required: true,
            message: this.$t("theProductNameCannotBeEmpty"),
            trigger: "blur",
          },
          {
            min: 2,
            max: 20,
            message: this.$t("theProductNameMustBeBetween2And20InLength"),
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    typetemplateValue(val) {},
  },
  created() {

    this.getList();
    this.getDeptTree();
    this.getConfigKey("sys.user.initPassword").then((response) => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    // 获取详情
    handleTypeTempClick() {
      this.getTypeTempDetails();
    },
    // 获取模版list
    getListTypetemplate() {
      typetemplates().then((response) => {
        this.typetemplateList = response.data;
        console.log("typetemplateList", this.typetemplateList);
      });
    },
    // 发送请求获取模版详情
    getTypeTempDetails() {
      findTypetemplateList(this.typetemplateValue).then((response) => {
        this.typeTempDetails = null;
        this.typeTempDetails = response;

        this.typeTempDetails.basicAttribute.forEach((item) => {
          // 使用 Vue.set 来动态添加响应式属性
          this.$set(this.basicForm, item.basicattributeProd, null);
          this.$set(this.basicFormLabel, item.basicattributeProd, item.basicattributeLabel);
        });
        this.typeTempDetails.publicAttribute.forEach((item) => {
          // 使用 Vue.set 来动态添加响应式属性
          this.$set(this.publicAttribute, item.publicattributeType, null);
          this.$set(this.publicattributeLabel, item.publicattributeType, item.publicattributeName);
        });

        this.deptAddOptions = this.deptOptions;

        typetemplatesProduct().then((response) => {
          this.$set(this.form, "heartbeatProduct", null);
          this.heartbeatProduct = response.data;
        });
      });
    },
    handleCheckedTreeExpand(value, type) {
      if (type == "menu") {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == "dept") {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },

    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == "menu") {
        this.$refs.menu.setCheckedNodes(value ? this.deptOptions : []);
      } else if (type == "dept") {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      }
    },


    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == "menu") {
        this.form.menuCheckStrictly = value ? true : false;
      } else if (type == "dept") {
        this.form.deptCheckStrictly = value ? true : false;
      }
    },

    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 查询用户列表 */
    getList() {
      refreshCache().then(() => {

        this.$store.dispatch('dict/cleanDict');
      });

      this.loading = true;
      listProducts(this.queryParams).then((response) => {
        this.productsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

      this.getListTypetemplate();
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;

      console.log(data.label.indexOf(value));
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.productModel = data.id;
      this.handleQuery();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '""' + row.userName + '"用户吗？')
        .then(function () {
          return changeUserStatus(row.userId, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }

      this.form = {
        productId: null,
        productName: null,
        productModel: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        productModelE: null,
        prodTypes: [],
        productImg: null,
        roles: [],
        productFile: null,
        heartbeatProduct: [],
        productNodFile: null,
        description: null,
        status: null,
        isPublish: null,
        sellingPoint: null,
        orderNum: null,
        productZip: null,
      };
      this.basicForm = {};
      this.publicAttribute = {};
      this.typetemplateValue = null;

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.productModel = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.productId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.isAdd = false;
      this.reset();
      this.typetemplateValue = null;
      getProductsAdd().then((response) => {
        this.$set(this.form, "isPublish", "0");
        this.receptionRole = response.receptionRole;
        this.products = response.products;
        this.open = true;
        this.title = this.$t("addProduct");
      });
    },
    getRoleMenuTreeselect(productId) {

      return getProducts(productId).then((response) => {
        return response;
      });
    },
    addTypetemplate(typetemplateValue) {
      this.deptAddOptions = this.deptOptions;


      findTypetemplateList(typetemplateValue).then((response) => {
        this.typetemplateValue = typetemplateValue;
        this.typeTempDetails = response;

      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isinpututool = false;
      this.typetemplateValue = null;
      const productId = row.productId || this.ids;
      this.addTypetemplate(row.prodTypeId);
      this.isAdd = true;
      getProducts(productId).then((response) => {
        this.form = response.data;
        const roleMenu = response.prodTypes;
      this.$forceUpdate()
        console.log('roleMenu',roleMenu);
      setTimeout(()=>{
        this.$nextTick(() => {
          roleMenu.forEach((v) => {
            this.$nextTick(() => {
              console.log(this.$refs.menu);
              this.$refs.menu.setChecked(v, true, false);
            });
          });
        });
      },200)

        const publicAttribute = JSON.parse(response.data.publicAttribute);
        const basicForm = JSON.parse(response.data.basicAttribute);

        for (const item in basicForm) {
          if (!this.basicForm) {
            this.basicForm = {};
          }
          console.log(item, basicForm[item]);
          this.$set(this.basicForm, item, basicForm[item]);

          this.basicForm[item] = basicForm[item];
        }
        for (const item in publicAttribute) {
          this.$set(this.publicAttribute, item, publicAttribute[item]);
          this.publicAttribute[item] = publicAttribute[item];
        }

        this.receptionRole = response.receptionRole;
        this.$set(this.form, "roles", response.roles);
        this.heartbeatProduct = response.heartbeatProducts;
        this.$set(this.form, "heartbeatProduct", response.heartbeatProductIds);

        this.open = true;
        this.title = this.$t('edit');
      });
    },

    /** 重置密码按钮操作 */
    handleResetPwd(row) {},
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },

    validBasicFormAndPublicAttr() {
      for (const key in this.basicForm) {
        if (this.basicForm.hasOwnProperty(key)) {
          if (
            this.basicForm[key] === null ||
            this.basicForm[key] === undefined
          ) {

            this.$modal.alertError(this.$t('input') + this.basicFormLabel[key] );
            return false;
          }
        }
      }

      for (const key in this.publicAttribute) {
        if (this.publicAttribute.hasOwnProperty(key)) {
          if (
            this.publicAttribute[key] === null ||
            this.publicAttribute[key] === undefined
          ) {
            this.$modal.alertError(this.$t('input')  +this.publicattributeLabel[key] );
            return false;
          }
        }
      }
      return true;
    },
    /** 提交按钮 */
    submitForm() {
      if (!this.validBasicFormAndPublicAttr()) {
        return false;
      }
      this.$refs["form"].validate((valid) => {
        this.form.basicAttribute = JSON.stringify(this.basicForm);
        this.form.publicAttribute = JSON.stringify(this.publicAttribute);
        this.form.prodTypeId = this.typetemplateValue + "";
        console.log("form:", this.form);
        if (valid) {
          if (this.form.productId != null) {
            if (this.form.isPublish == "0") {
              this.$set(this.form, "sellingPoint", null);
              this.$set(this.form, "orderNum", null);
            }
            this.form.prodTypes = this.getMenuAllCheckedKeys();
            updateProducts(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t('modifiedSuccessfully'));
              this.typetemplateValue = null;
              this.open = false;
              this.getList();
            });
          } else {
            this.form.prodTypes = this.getMenuAllCheckedKeys();
            addProducts(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t('newSuccessfullyAdded'));
              this.typetemplateValue = null;
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids;
      this.$modal
        .confirm(
          this.$t("areYouSureYouWantToDeleteTheDataItemWithTypeNumber") +
          '"' +
          productIds +
          '"'
        )
        .then(function () {
          return delProducts(productIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("deleteSuccessfully"));
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/products/export",
        {
          ...this.queryParams,
        },
        `产品_${new Date().getTime()}.xlsx`
      );
    },
    handleImportTemplate() {},
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },

    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
